package com.yzycoc.util;


import java.nio.charset.StandardCharsets;

/**
 * 字符集工具类
 * @author: yzy
 * 2020-08-24 20:48
 * v1.0
 **/
public class Utf8Util {
    /**
     * 获取字符串的unicode编码
     * 汉字“木”的Unicode 码点为Ox6728
     *
     * @param str 字符串
     * @return unicode编码
     */
    public static String stringToUnicode(String str) {
        StringBuffer sb = new StringBuffer();
        char[] c = str.toCharArray();
        for (int i = 0; i < c.length; i++) {
            sb.append("\\u" + Integer.toHexString(c[i]));
        }
        return sb.toString();
    }

    /**
     * unicode转字符串
     *
     * @param unicode unicode
     * @return 字符串
     */
    public static String unicodeToString(String unicode) {
        StringBuffer sb = new StringBuffer();
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            int index = Integer.parseInt(hex[i], 16);
            sb.append((char) index);
        }
        return sb.toString();
    }

    /***
     * 字符集转换 数据库认可
     * @param key 需要转换的值
     * @return string
     */
    public static String Mybatislike(String key) {
        if(key == null || key.length() == 0) {
            return key;
        }
        return key.replace("\\", "\\\\").replace("%", "\\%").replace("％", "\\％")
                .replace("_", "\\_").replace("＿", "\\＿").replace("'", "''");
    }


    /***
     * 字符串转 16进制数据
     * @param val 字符串
     * @return 16进进制 数据
     */
    public static String stringToHex(String val) {
        byte[] bytes = val.getBytes(StandardCharsets.UTF_8);
        byte[] head = new byte[3];
        head[0] = 1;
        byte[] all = addAll(head, bytes);
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < all.length; i++) {
            result.append(Integer.toHexString((all[i] & 0xFF | 0xFFFFFF00)).substring(6));
            if (i < all.length - 1) {
                result.append(",");
            }
        }
        return result.toString();
    }


    private static byte[] addAll(byte[] array1, byte[] array2) {
        if (array1 == null) {
            return clone(array2);
        } else if (array2 == null) {
            return clone(array1);
        } else {
            byte[] joinedArray = new byte[array1.length + array2.length];
            System.arraycopy(array1, 0, joinedArray, 0, array1.length);
            System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
            return joinedArray;
        }
    }

    public static byte[] clone(byte[] array) {
        return array == null ? null : (byte[])((byte[])array.clone());
    }
}
